<template>
  <div>
    <div class="d-flex">
      <div
        class="m-r-mini c-pointer one-photo-button"
        @click="startPick"
      >
        <i class="el-icon-location-outline f-20" />
        地图点选
      </div>
      <el-select
        v-model="value"
        filterable
        remote
        placeholder="请输入站点名称或编号"
        size="small"
        class="theme-select"
        popper-class="theme-popper"
        :remote-method="remoteMethod"
        :loading="loading"
        style="width: 254px;"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          @click.native="changeValue(item.value)"
        />
      </el-select>
    </div>
    <div
      v-show="needSearchTzz && coordinate.length && ht && cv"
      class="d-flex-c theme-container p-a-mini m-t-mini"
      style="border-radius: 4px;"
    >
      <span
        class="m-b-mini flex-between"
        v-if="isPick && coordinate.length"
      >目标坐标：{{ `Ⓔ ${$helper.formatDegree(coordinate[0])} Ⓝ ${$helper.formatDegree(coordinate[1])}` }} <i
        class="el-icon-close c-pointer"
        @click="clearPoint"
      /></span>
      <span
        class="m-b-mini flex-between"
        v-if="!isPick && coordinate.length"
      >目标测站：{{ currentName }}<i
        class="el-icon-close c-pointer"
        @click="clearPoint"
      /></span>
      <span class="m-b-mini">历时：{{ lsName }}</span>
      <span>Ht: {{ ht + 'mm' }} Cv: {{ cv }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SearchStation',
  props: {
    ls: {
      type: String,
      default: ''
    },
    needSearchTzz: {
      type: Boolean,
      default: false
    },
    expand: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      value: '',
      raw: [],
      loading: false,
      options: [],
      coordinate: [],
      ht: '',
      cv: '',
      lsName: '',
      isPick: false,
      currentName: '',
      isActive: false
    }
  },
  created () {
    if (this.needSearchTzz) {
      this.$root.$on('getHtAndCvByPosition', this.getHtAndCv)
    } else {
      this.$mapManager.addEventListener('closeMapTool', this.closeMapTool)
    }
  },
  beforeDestroy () {
    if (this.needSearchTzz) {
      this.$root.$off('getHtAndCvByPosition', this.getHtAndCv)
    } else {
      this.$mapManager.removeEventListener('closeMapTool', this.closeMapTool)
    }
  },
  methods: {
    async remoteMethod (keywords) {
      this.loading = true
      if (keywords) {
        const { rows } = await this.$request.singleTableOperation({
          url: '/grid/getTableData',
          metaSet: 'YSQJC_ST_STBPRP_B_CB',
          methodCode: 'getCZList',
          methodParams: {
            CZXX: keywords
          },
          pageSize: 20,
          pageNum: 1
        })
        this.options = rows.map(item => ({ label: `${item.STNM} ${item.STCD}`, value: item.STCD, ...item }))
      } else {
        this.options = []
      }
      this.loading = false
    },
    async changeValue (v) {
      this.ht = ''
      this.cv = ''
      const station = this.options.find(item => item.value === v)
      if (!station.LGTD || !station.LTTD) {
        this.$message.warning('该测站没有经纬度数据')
        return
      }
      const layerId = 'station_' + (['DD', 'PP', 'RR', 'ZQ', 'ZZ'].includes(station.STTP) ? station.STTP : 'QT')
      const layer = await this.$mapManager.invokeUtils('getLayer', layerId)
      if (!layer.getVisible()) {
        await this.$mapManager.invoke('setLayerVisible', layerId, true)
        this.$mapManager.emit('updateLayer')
      }
      this.coordinate = [station.LGTD, station.LTTD]
      this.isPick = false
      const [feature] = layer.getSource().getFeaturesAtCoordinate(this.coordinate)
      this.$mapManager.invoke('fit', feature.getGeometry(), { maxZoom: 13, duration: 0, padding: this.expand ? [0, 550, 0, 0] : [0, 0, 0, 0] })
      if (this.needSearchTzz) {
        // this.getHtAndCv(this.coordinate)
      } else {
        this.currentName = station.STNM + ' ' + station.STCD
        this.$root.$emit('mapPick', { coordinate: this.coordinate, name: this.currentName, id: station.STCD })
      }
      setTimeout(() => {
        this.$mapManager.invoke('selectFeature', feature)
      }, 400)
    },
    getStyle () {
      const iconOption = new window.ol.style.Icon({
        offset: [0, 0],
        opacity: 1,
        scale: 0.8,
        src: require('@/assets/images/map/point-station.png'),
        size: [58, 200]
      })
      const option = { image: iconOption }
      return new window.ol.style.Style(option)
    },
    selectStyle (feature) {
      const iconOption = new window.ol.style.Icon({
        offset: [0, 0],
        opacity: 1,
        scale: 0.8,
        src: require('@/assets/images/map/point-station.png'),
        size: [58, 200]
      })
      const option = { image: iconOption }
      feature.setStyle(new window.ol.style.Style(option))
    },
    async startPick () {
      this.ht = ''
      this.cv = ''
      if (this.needSearchTzz) {
        this.isPick = true
        document.querySelector('body').style.cursor = 'crosshair'
        this.$root.$off('mapClick', this.handleMapClick)
        this.$root.$on('mapClick', this.handleMapClick)
      } else {
        const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
        this.features = layer.getSource().getFeatures()
        layer.getSource().clear()
        this.$mapManager.invoke('showTool')
        this.$mapManager.invoke('startDrawByOptions', { type: 'Point', eventKey: 'pick' })
      }
    },
    async closeMapTool (isClose) {
      if (this.features && this.features.length && isClose) {
        const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
        layer.getSource().addFeatures(this.features)
        this.features = null
      }
    },
    handleMapClick (e) {
      this.coordinate = e
      this.$root.$off('mapClick', this.handleMapClick)
      document.querySelector('body').style.cursor = 'default'
      if (this.needSearchTzz) {
        this.getHtAndCv()
      } else {
        this.$root.$emit('mapPick', { coordinate: this.coordinate })
      }
    },
    async getHtAndCv (data) {
      if (data) {
        this.coordinate = data.coordinate
        this.currentName = data.name
      }
      if (!this.coordinate.length) return
      const feature = new window.ol.Feature(new window.ol.geom.Point(this.coordinate))
      const wkt = await this.$mapManager.invoke('transfromFeature', feature, false)
      const { ht, cv, cvdata, htdata, msg } = await this.$request.post('/ysjc/bytjjs/getpitcvht', { point: wkt, ht: this.ls })
      this.ht = ht || ''
      this.cv = cv || ''
      const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
      layer.getSource().clear()
      cvdata && this.renderLine(cvdata, feature, layer, 'cv')
      htdata && this.renderLine(htdata, feature, layer, 'ht')
      this.lsName = await this.$utils.dictionary.getOptionNameByValue('YSQJC_JC_BYTJBZLS', this.ls)
      if (msg) {
        this.$message.warning(msg)
      }
    },
    clearPoint () {
      this.$mapManager.invoke('clearLayers', ['graphicLayer', 'modifylayer'])
      this.coordinate = []
      this.ht = ''
      this.cv = ''
      this.currentName = ''
    },
    async renderLine (data, point, layer, type) {
      const list = []
      const values = []
      for (const item of data) {
        const point = item ? await this.$mapManager.invoke('transfromFeature', item.foot_point) : null
        list.push(point.getGeometry().getCoordinates())
        values.push(item.tzzl)
      }
      list.splice(1, 0, point.getGeometry().getCoordinates())
      const lineGeom = new window.ol.geom.LineString(list)
      const feature = new window.ol.Feature()
      feature.setGeometry(lineGeom)
      feature.setProperties({ type, values })
      feature.setStyle(this.getLineStyle)
      layer.getSource().addFeature(feature)
    },
    getLineStyle (feature) {
      const { type, values } = feature.getProperties()
      const styles = []
      styles.push(new window.ol.style.Style({
        stroke: new window.ol.style.Stroke({
          color: type === 'cv' ? '#7019ff' : '#e04545',
          width: 2,
          lineDash: [10, 10]
        }),
        image: new window.ol.style.Circle({
          radius: 4,
          fill: new window.ol.style.Fill({
            color: '#ffff'
          }),
          stroke: new window.ol.style.Stroke({
            color: type === 'cv' ? '#7019ff' : '#e04545',
            width: 2
          })
        })
      }))
      styles.push(
        new window.ol.style.Style({
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()
            const points = [coordinates[0]]
            if (coordinates.length > 2) {
              points.push(coordinates[2])
            }
            return new window.ol.geom.MultiPoint(points)
          },
          image: new window.ol.style.Circle({
            radius: 4,
            fill: new window.ol.style.Fill({
              color: '#ffff'
            }),
            stroke: new window.ol.style.Stroke({
              color: type === 'cv' ? '#7019ff' : '#e04545',
              width: 2
            })
          })
        })
      )
      styles.push(
        new window.ol.style.Style({
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()
            return new window.ol.geom.Point(coordinates[1])
          },
          image: new window.ol.style.Circle({
            radius: 6,
            fill: new window.ol.style.Fill({
              color: '#ffff'
            }),
            stroke: new window.ol.style.Stroke({
              color: '#00dc10',
              width: 2
            })
          })
        })
      )
      const firstCoordinates = feature.getGeometry().getFirstCoordinate()
      const list = [firstCoordinates]
      if (feature.getGeometry().getCoordinates().length > 2) {
        const lastCoordinates = feature.getGeometry().getLastCoordinate()
        list.push(lastCoordinates)
      }
      list.forEach((item, i) => {
        styles.push(new window.ol.style.Style({
          geometry: new window.ol.geom.Point(item),
          text: new window.ol.style.Text({
            font: 'bold 0.8rem sans-serif',
            text: values[i].toString(),
            fill: new window.ol.style.Fill({
              color: type === 'cv' ? '#7019ff' : '#e04545'
            }),
            offsetY: 20
          })
        }))
      })
      return styles
    }
  }
}
</script>

<style lang="scss" scoped>
.one-photo-button {
  background: rgba($color: #fff, $alpha: 0.8);
  padding: 6px 10px;
  border: 1px solid #b7b9bb;
  border-radius: 4px;
  color: #424e61;
  font-size: 14px;
  display: flex;
  align-items: center;
  width: 104px;

  &:hover {
    background: #fff !important;
  }
}
</style>
